// 账号管理
import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Space, Table, message, Pagination, Form, Input, InputNumber, TreeSelect,Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import type { TableColumnsType, FormInstance } from 'antd';
import { getLevelList, createLevel, updateLevel, deleteLevel } from '@/api/level';

interface LevelItem {
  id: string;
  title: string;
  money: string;
  safe: string;
  station: string;
  between: string;
  performance: string;
  pid: string | number | null;
  children?: LevelItem[];
}

// 树形结构节点接口
interface TreeNode extends LevelItem {
  value: string;
  money: number;
  children?: TreeNode[];
}

// 表单数据接口
interface LevelFormData {
  id?: string;
  title: string;
  money: number;
  safe: number;
  station: number;
  between: string;
  performance: number;
  pid: string | number | null;
}

const LevelPage: React.FC = () => {
   const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = useState('确定要删除当前档级吗(请谨慎操作)');
  const { initialState } = useModel('@@initialState');
  const [data, setData] = React.useState<TreeNode[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [expandedRowKeys, setExpandedRowKeys] = React.useState<React.Key[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [form] = Form.useForm<LevelFormData>();
  
// 提示框
  const showModal = () => {
    setOpen(true);
  };

  const handleOk = () => {
    setModalText('The modal will be closed after two seconds');
    setConfirmLoading(true);
    setTimeout(() => {
      setOpen(false);
      setConfirmLoading(false);
    }, 2000);
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };
  


  // 递归函数：将扁平的档级数据转换为树形结构
  const buildLevelTree = (items: LevelItem[]): TreeNode[] => {
    if (!items || items.length === 0) {
      return [];
    }

    // 将所有项转换为TreeNode格式
    const nodeMap: Record<string, TreeNode> = {};
    items.forEach((item) => {
      // 修复pid等于自身id的情况
      let pid = item.pid;
      if (pid && String(pid) === String(item.id)) {
        pid = null; // 将pid设置为null，使其成为根节点
      }
      
      nodeMap[item.id] = {
        title: item.title,
        value: String(item.id),
        money: parseFloat(item.money) || 0,
        pid: pid,
        ...item,
      };
    });

    // 构建树形结构
    const tree: TreeNode[] = [];
    items.forEach((item) => {
      const node = nodeMap[item.id];
      const parentId = node.pid;

      // 如果是根节点 (pid为0、"0"、null或undefined)
      if (!parentId || parentId === 0 || parentId === '0') {
        tree.push(node);
      } else {
        // 如果有父节点，则添加到父节点的children中
        const parentNodeId = String(parentId);
        if (nodeMap[parentNodeId]) {
          if (!nodeMap[parentNodeId].children) {
            nodeMap[parentNodeId].children = [];
          }
          nodeMap[parentNodeId].children!.push(node);
        } else {
          // 父节点不存在时，作为根节点处理
          tree.push(node);
        }
      }
    });

    return tree;
  };

  // 转换树形数据为TreeSelect可用的格式
  const convertToTreeSelectData = (tree: TreeNode[]): any[] => {
    return tree.map(node => ({
      title: node.title,
      value: node.id,
      key: node.id,
      children: node.children ? convertToTreeSelectData(node.children) : undefined
    }));
  };

  // 获取档级列表数据
  const fetchLevelList = async () => {
    setLoading(true);
    try {
      const res: any = await getLevelList({
        page: currentPage,
        pageSize: pageSize
      });
      if (res && res.code === 1 && res.list) {
        // 构建树形结构
        const treeData = buildLevelTree(res.list);
        setData(treeData);
        setTotal(res.total || treeData.length);
      } else {
        message.error(res?.msg || '获取档级列表失败');
      }
    } catch (error) {
      console.error('获取档级列表失败:', error);
      message.error('获取档级列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLevelList();
  }, [currentPage, pageSize]);

  // 处理分页变化
  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 切换行展开状态
  const toggleRowExpand = (key: React.Key) => {
    if (expandedRowKeys.includes(key)) {
      setExpandedRowKeys(expandedRowKeys.filter(k => k !== key));
    } else {
      setExpandedRowKeys([...expandedRowKeys, key]);
    }
  };

  // 打开新增弹窗
  const handleAdd = () => {
    setModalType('add');
    form.resetFields();
    setIsModalVisible(true);
  };

  // 打开编辑弹窗
  const handleEdit = (record: TreeNode) => {
    setModalType('edit');
    form.setFieldsValue({
      id: record.id,
      title: record.title,
      money: parseFloat(record.money.toString()),
      safe: parseFloat(record.safe),
      station: parseFloat(record.station),
      between: record.between,
      performance: parseFloat(record.performance),
      pid: record.pid && record.pid !== '0' && record.pid !== 0 ? record.pid : null
    });
    setIsModalVisible(true);
  };
 // 关闭新增/编辑弹窗
  const handleModalCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const formData: LevelFormData = { ...values };

      setLoading(true);
      let res: any;
      
      if (modalType === 'add') {
        res = await createLevel(formData);
      } else {
        res = await updateLevel(formData);
      }

      if (res && res.code === 1) {
        message.success(modalType === 'add' ? '新增成功' : '编辑成功');
        setIsModalVisible(false);
        fetchLevelList(); // 重新获取列表数据
      } else {
        message.error(res?.msg || (modalType === 'add' ? '新增失败' : '编辑失败'));
      }
    } catch (error) {
      console.error(modalType === 'add' ? '新增失败:' : '编辑失败:', error);
      message.error(modalType === 'add' ? '新增失败' : '编辑失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除档级
  const handleDelete = async (id: string) => {
    try {
      setLoading(true);
      // 确保传递正确的参数格式
      const res: any = await deleteLevel({id});
      if (res && res.code === 1) {
        message.success('删除成功');
        fetchLevelList(); // 重新获取列表数据
      } else {
        message.error(res?.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

   // 添加删除确认函数
  const showDeleteConfirm = (id: string) => {
    Modal.confirm({
      title: '确定要删除该档级吗？',
      content: '删除后不可恢复，请谨慎操作！',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        return handleDelete(id);
      },
      onCancel() {
        console.log('取消删除');
      },
    });
  };

  const columns: TableColumnsType<TreeNode> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '6%',
    },
    {
      title: '档级名称',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {record.children && record.children.length > 0 && (
            <span 
              style={{ 
                marginRight: 8, 
                cursor: 'pointer',
                transform: expandedRowKeys.includes(record.id) ? 'rotate(90deg)' : 'rotate(0deg)',
                display: 'inline-block',
                transition: 'transform 0.2s'
              }} 
              onClick={(e) => {
                e.stopPropagation();
                toggleRowExpand(record.id);
              }}
            >
              ▶
            </span>
          )}
          <span>{record.title}</span>
        </div>
      )
    },
    {
      title: '岗位薪资',
      dataIndex: 'money',
      key: 'money',
      width: '12%',
      render: (text) => `${parseFloat(text.toString()).toFixed(2)}`,
    },
    {
      title: '安全质量奖',
      dataIndex: 'safe',
      key: 'safe',
      width: '12%',
      render: (text) => `${parseFloat(text.toString()).toFixed(2)}`,
    },
    {
      title: '岗位津贴',
      dataIndex: 'station',
      key: 'station',
      width: '12%',
      render: (text) => `${parseFloat(text.toString()).toFixed(2)}`,
    },
    {
      title: '薪资区间',
      dataIndex: 'between',
      key: 'between',
      width: '15%',
      render: (text) => text || '-'
    },
    {
      title: '绩效薪资',
      dataIndex: 'performance',
      key: 'performance',
      width: '12%',
      render: (text) => `${parseFloat(text.toString()).toFixed(2)}`,
    },
     {
      title: '操作',
      key: 'action',
      width: '16%',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="primary" danger onClick={() => showDeleteConfirm(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];


  return (
    <PageContainer style={{ backgroundColor: 'white' }}>
      <div style={{ width: '100%', marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <div>
          <Button type="primary" style={{ marginRight: 8 }} onClick={handleAdd}>
            新增
          </Button>
        </div>
      </div>
      <Table<TreeNode>
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={false}
        expandedRowKeys={expandedRowKeys}
        onExpandedRowsChange={(keys) => setExpandedRowKeys(keys as string[])}
        rowKey="id"
        expandable={{
          expandedRowKeys,
          onExpandedRowsChange: (keys) => setExpandedRowKeys(keys as string[]),
          // 隐藏默认的展开图标
          expandIcon: () => null
        }}
      />
      <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={total}
          onChange={handlePageChange}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条记录`}
        />
      </div>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={modalType === 'add' ? '新增档级' : '编辑档级'}
        open={isModalVisible}
        onCancel={handleModalCancel}
        footer={[
          <Button key="cancel" onClick={handleModalCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
            {modalType === 'add' ? '新增' : '保存'}
          </Button>,
        ]}
        destroyOnClose
        maskClosable={false}
        width={600}
      >
        <Form
          form={form}
          name="level_form"
          initialValues={{ pid: null }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Form.Item
            name="id"
            hidden
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="pid"
            label="选择上级"
          >
            <TreeSelect
              treeData={convertToTreeSelectData(data)}
              placeholder="请选择"
              treeDefaultExpandAll
              allowClear
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="title"
            label="档级名称"
            rules={[
              { required: true, message: '请输入档级名称' },
              { max: 50, message: '档级名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入档级名称" maxLength={50} />
          </Form.Item>

          <Form.Item
            name="money"
            label="岗位薪资"
            rules={[
              { required: true, message: '请输入岗位薪资' },
              { type: 'number', min: 0, message: '岗位薪资必须为非负数' },
            ]}
          >
            <InputNumber 
              placeholder="请输入岗位薪资" 
              style={{ width: '100%' }}
              precision={2}
            />
          </Form.Item>

          <Form.Item
            name="safe"
            label="安全质量奖"
            rules={[
              { required: true, message: '请输入安全质量奖' },
              { type: 'number', min: 0, message: '安全质量奖必须为非负数' },
            ]}
          >
            <InputNumber 
              placeholder="请输入安全质量奖" 
              style={{ width: '100%' }}
              precision={2}
            />
          </Form.Item>

          <Form.Item
            name="station"
            label="岗位津贴"
            rules={[
              { required: true, message: '请输入岗位津贴' },
              { type: 'number', min: 0, message: '岗位津贴必须为非负数' },
            ]}
          >
            <InputNumber 
              placeholder="请输入岗位津贴" 
              style={{ width: '100%' }}
              precision={2}
            />
          </Form.Item>


          <Form.Item
            name="between"
            label="档级薪资区间"
            rules={[
              { required: true, message: '请输入档级薪资区间' },
              { max: 50, message: '薪资区间不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入档级薪资区间" maxLength={50} />
          </Form.Item>

          <Form.Item
            name="performance"
            label="绩效薪资"
            rules={[
              { required: true, message: '请输入绩效薪资' },
              { type: 'number', min: 0, message: '绩效薪资必须为非负数' },
            ]}
          >
            <InputNumber 
              placeholder="请输入绩效薪资" 
              style={{ width: '100%' }}
              precision={2}
            />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="档级删除"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <p>{modalText}</p>
      </Modal>
    </PageContainer>
  );
};

export default LevelPage;